package com.cb.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cb.spzx.common.exception.CbException;
import com.cb.spzx.manager.mapper.SysUserRoleMapper;
import com.cb.spzx.manager.service.SysRoleService;
import com.cb.spzx.manager.service.SysUserRoleService;
import com.cb.spzx.manager.service.SysUserService;
import com.cb.spzx.manager.mapper.SysUserMapper;
import com.cb.spzx.model.common.Constant;
import com.cb.spzx.model.dto.h5.UserResetPwdDto;
import com.cb.spzx.model.dto.system.AssginRoleDto;
import com.cb.spzx.model.dto.system.LoginDto;
import com.cb.spzx.model.dto.system.SysUserDto;
import com.cb.spzx.model.entity.system.SysRoleUser;
import com.cb.spzx.model.entity.system.SysUser;
import com.cb.spzx.model.vo.common.ResultCodeEnum;
import com.cb.spzx.model.vo.system.LoginVo;
import com.cb.spzx.utils.AuthContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author lenovo
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2024-04-09 17:29:58
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public LoginVo login(LoginDto loginDto) {
        // 校验验证码是否正确
        String captcha = loginDto.getCaptcha(); // 用户输入的验证码
        String key = loginDto.getCodeKey(); // redis中验证码的数据key\
        // 从Redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get(Constant.CODE_VALIDATE + key);
        if (StrUtil.isEmpty(redisCode)||!StrUtil.equalsIgnoreCase(captcha,redisCode)) {
            throw new CbException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        // 验证通过删除redis中的验证码
        redisTemplate.delete(Constant.CODE_VALIDATE+key);

        //根据用户名查询用户
        String userName = loginDto.getUserName();
        SysUser sysUser = getSysUser(userName);
        if (sysUser==null) {
            //throw new RuntimeException("用户名不存在！");
            throw new CbException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 验证密码是否正确
        String database_pwd = sysUser.getPassword();
        String input_pwd = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        if (!input_pwd.equals(database_pwd)) {
            //throw new RuntimeException("密码不正确！");
            throw new CbException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 生成令牌，保存数据到Redis中
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(Constant.USER_INFO +token, JSON.toJSONString(sysUser),7, TimeUnit.DAYS);
        // 构建响应结果对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    //根据用户名查询用户
    private SysUser getSysUser(String userName) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUserName, userName);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get(Constant.USER_INFO + token);
        return JSON.parseObject(userJson,SysUser.class);
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(Constant.USER_INFO+token);
    }

    @Override
    public IPage<SysUser> findByPage(SysUserDto sysUserDto, Page<SysUser> sysUserPage) {
        String keyword = sysUserDto.getKeyword();
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StrUtil.isEmpty(keyword),SysUser::getUserName,keyword)
                .or().like(!StrUtil.isEmpty(keyword),SysUser::getName,keyword)
                .or().like(!StrUtil.isEmpty(keyword),SysUser::getPhone,keyword);
        queryWrapper.ge(!StrUtil.isEmpty(sysUserDto.getCreateTimeBegin()),SysUser::getCreateTime,sysUserDto.getCreateTimeBegin());
        queryWrapper.le(!StrUtil.isEmpty(sysUserDto.getCreateTimeEnd()),SysUser::getCreateTime,sysUserDto.getCreateTimeEnd());
        queryWrapper.orderByDesc(SysUser::getCreateTime);
        return baseMapper.selectPage(sysUserPage,queryWrapper);
    }

    @Override
    public int saveSysUser(SysUser sysUser) {
        // 根据输入的用户名查询用户
        String userName = sysUser.getUserName();
        SysUser sysUser1 = getSysUser(userName);
        if (sysUser1!=null) {
            throw new CbException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        //密码进行加密，默认密码111111
        String pwd = DigestUtils.md5DigestAsHex(Constant.DEFAULT_USER_PWD.getBytes());
        sysUser.setPassword(pwd);
        return baseMapper.insert(sysUser);
    }

    @Override
    public int updateSysUser(SysUser sysUser) {
        sysUser.setUpdateTime(new Date());
        return baseMapper.updateById(sysUser);
    }

    @Override
    public int deleteById(Long userId) {
        return baseMapper.deleteById(userId);
    }

    @Transactional
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        // 删除之前的所有的用户所对应的角色数据
        LambdaQueryWrapper<SysRoleUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleUser::getUserId,assginRoleDto.getUserId());
        Long count = sysUserRoleMapper.selectCount(queryWrapper);
        if(count!=0){
            sysUserRoleMapper.delete(queryWrapper);
        }
        // 分配新的角色数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        for (Long roleId : roleIdList) {
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUserId(assginRoleDto.getUserId());
            sysRoleUser.setRoleId(roleId);
            sysRoleUser.setCreateTime(new Date());
            sysRoleUser.setUpdateTime(new Date());
            sysUserRoleMapper.insert(sysRoleUser);
        }
    }

    @Override
    public void updateInfo(SysUser sysUser,String token) {
        //当前登录用户ID
        Long id = AuthContextUtil.get().getId();
        //修改
        LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysUser::getId,id);
        sysUser.setUpdateTime(new Date());
        int update = baseMapper.update(sysUser, updateWrapper);
        if(update>0){
            //刷新redis中用户信息
            SysUser sysUser1 = baseMapper.selectById(id);
            redisTemplate.opsForValue().set(Constant.USER_INFO +token, JSON.toJSONString(sysUser1),7, TimeUnit.DAYS);
        }
    }

    @Override
    public void resetPwd(UserResetPwdDto userResetPwdDto) {
        System.out.println(userResetPwdDto);
        String old_pwd = DigestUtils.md5DigestAsHex(userResetPwdDto.getOldPwd().getBytes());
        String new_pwd = DigestUtils.md5DigestAsHex(userResetPwdDto.getNewPwd().getBytes());
        //当前登录用户ID
        Long id = AuthContextUtil.get().getId();
        //根据ID查询用户信息
        SysUser sysUser = baseMapper.selectById(id);
        String dbPwd = sysUser.getPassword();
        if(!dbPwd.equals(old_pwd)){
            throw new CbException(ResultCodeEnum.OLDPWD_ERROR);
        }
        if(!userResetPwdDto.getNewPwd().equals(userResetPwdDto.getConfirmPwd())){
            throw new CbException(ResultCodeEnum.TOWPWD_ERROR);
        }
        SysUser user = new SysUser();
        user.setId(id);
        user.setPassword(new_pwd);
        baseMapper.updateById(user);
    }
}




